﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using System.Xml;
using System.Reflection;
using MS.InformationManagement.Support.Constants;
using System.Web.UI.WebControls;
using System.Collections;

namespace MS.InformationManagement.Support
{
    public static class WindowExtensionHelper
    {
        public static void RegisterAjaxLoaderPlugin(this Page page)
        {
            page.ClientScript.RegisterClientScriptInclude("ajaxloader", "/_layouts/INC/MS.InformationManagement/JS/jquery.loading.debug.js");
        }

        public static void OpenDocument(this UserControl input, string documentPath)
        {
            StringBuilder jsBuilder = new StringBuilder("<script type='text/javascript'>ExecuteOrDelayUntilScriptLoaded(function(){ editDocumentWithProgID2('");
            jsBuilder.Append(string.Format("{0}', '', 'SharePoint.OpenDocuments', '0', '', '0');", documentPath))
                     .Append("}, 'sp.js');</script>");
            input.Page.ClientScript.RegisterClientScriptBlock(jsBuilder.GetType(), "customOpenDocuments", jsBuilder.ToString());
        }

        public static void ShowAlertMessageAndRedirect(this UserControl Input, string message, string url)
        {
            StringBuilder sb = new StringBuilder()
            .Append("$(document).ready(function ()")
            .Append(string.Format("{{ jAlert('{0}','Mensaje',function(r) {{", message))
            .Append(string.Format("window.location='{0}';}});}}); ", url));
            Input.Page.ClientScript.RegisterClientScriptBlock(sb.GetType(), "alertRedirect", sb.ToString(), true);
        }

        public static void ShowAlertMessageAndRedirect(this LayoutsPageBase Input, string message, string url)
        {
            StringBuilder sb = new StringBuilder()
                                .Append("$(document).ready(function ()")
                                .Append(string.Format("{{ jAlert('{0}','Mensaje',function(r) {{", message))
                                .Append(string.Format("window.location='{0}';}});}}); ", url));
            Input.Page.ClientScript.RegisterClientScriptBlock(sb.GetType(), "alertRedirect", sb.ToString(), true);
        }

        public static void GoCurrentUserHome(this LayoutsPageBase Input)
        {
            Input.Page.Response.Write(string.Format("<script type='text/javascript'>window.location='{0}'</script>", ListHelper.CurrentUserLibraryUrl));
        }

        public static void GoCurrentUserHome(this UserControl Input)
        {
            Input.Page.Response.Write(string.Format("<script type='text/javascript'>window.location='{0}'</script>", ListHelper.CurrentUserLibraryUrl));
        }

        public static void _ShowAlertAndClose(this UserControl Input, string message)
        {
            StringBuilder sb = new StringBuilder()
            .Append("$(document).ready(function (){{ jAlert('" + message + "','Mensaje',function(r) {{window.frameElement.commitPopup();}});}});");
            Input.Page.ClientScript.RegisterClientScriptBlock(sb.GetType(), "alertRedirect", sb.ToString(), true);
        }

        public static void ShowAlertAndClose(this UserControl Input, string message)
        {
            Input.Page.Response.Write("<script type='text/javascript'>alert('" + message + "','')</script>");
            Input.Page.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
        }

        public static void ShowAlertAndClose(this LinkButton Input, string message)
        {

            Input.Page.Response.Write("<script type='text/javascript'>alert('" + message + "','')</script>");
            Input.Page.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
        }

        public static void CloseWindow(this UserControl Input)
        {
            Input.Page.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
        }

        public static void CloseWindowWithResponse(this LayoutsPageBase Input, string dialogResponse)
        {
            Input.Page.Response.Write(string.Format("<script type='text/javascript'>window.frameElement.commitPopup(\"{0}\");</script>", dialogResponse));
            Input.Page.Response.Flush();
            Input.Page.Response.End();
        }

        public static void CloseWindowWithResponse(this UserControl Input, string dialogResponse)
        {
            Input.Page.Response.Write(string.Format("<script type='text/javascript'>window.frameElement.commitPopup(\"{0}\");</script>", dialogResponse));
            Input.Page.Response.Flush();
            Input.Page.Response.End();
        }

        public static void CloseWindow(this LayoutsPageBase Input)
        {
            Input.CloseWindow(true);
        }

        public static void CloseWindow(this LayoutsPageBase Input, bool isModal)
        {
            if (isModal)
            {
                Input.Page.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup(1);</script>");
                Input.Page.Response.Flush();
                Input.Page.Response.End();
            }
            else
            {
                Input.Page.Response.Write(string.Format("<script type='text/javascript'>window.location='{0}';</script>", ListHelper.CurrentUserLibraryUrl));
                Input.Page.Response.Flush();
                Input.Page.Response.End();
            }
        }

        public static void DesplegarVentanaModal(this UserControl Input, string Url, string Titulo, Int32 ancho, Int32 alto, Page pagina)
        {
            StringBuilder scriptModal = new StringBuilder();
            scriptModal.Append("var showMyModalDialog = function() { var options = { ");
            scriptModal.Append("url : '");
            scriptModal.Append(Url);
            scriptModal.Append("', ");
            scriptModal.Append("title: '");
            scriptModal.Append(Titulo);
            scriptModal.Append("', width: ");
            scriptModal.Append(ancho.ToString());
            scriptModal.Append(", height: ");
            scriptModal.Append(alto.ToString());
            scriptModal.Append(", dialogReturnValueCallback: RefreshPage }; SP.UI.ModalDialog.commonModalDialogOpen(" + "'" + Url + "'" + ",options, onDialogClose, null); };");
            scriptModal.Append("function onDialogClose(dialogResult, returnValue) { ");
            scriptModal.Append("if(returnValue){ window.location= window.location.search = '?remitenteID=' + returnValue; }else{  SP.UI.ModalDialog.close(SP.UI.DialogResult.cancel); } ");
            scriptModal.Append(" } ");

            pagina.ClientScript.RegisterClientScriptBlock(pagina.GetType(), "Mensaje", scriptModal.ToString(), true);
            pagina.ClientScript.RegisterStartupScript(typeof(Page), "Precarga", "ExecuteOrDelayUntilScriptLoaded(showMyModalDialog, 'sp.ui.dialog.js');", true);
        }

        public static void ShowAlertAndClose(this LayoutsPageBase Input, string message)
        {
            Input.Page.Response.Write("<script type='text/javascript'>alert('" + message + "','')</script>");
            Input.Page.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
        }

        public static void _ShowAlertAndClose(this LayoutsPageBase Input, string message)
        {
            StringBuilder sb = new StringBuilder()
            .Append("$(document).ready(function (){{ jAlert('" + message + "','Mensaje',function(r) {{window.frameElement.commitPopup();}});}});");
            Input.Page.ClientScript.RegisterClientScriptBlock(sb.GetType(), "alertRedirect", sb.ToString(), true);
        }

        public static void OpenDialog(this HyperLink control, string url)
        {
            control.Attributes.Add("onclick", OpenUrl(url));
        }

        public static void OpenDialog(this UserControl control, string url)
        {
            control.Attributes.Add("onclick", OpenUrl(url));
        }

        public static string OpenUrl(string url)
        {
            return "openDialogAutoSize('" + url + "'); return false;";
        }

        public static void RemoveLeftColumn(UserControl input)
        {
            if (SPContext.Current.List != null && !SPContext.Current.List.BaseTemplate.ToString().Equals(GlobalConstants.GLOBAL_USER_LIBRARY_TEMPLATE))
            {
                Literal cssFile = new Literal() { Text = @"<link rel=""stylesheet"" type=""text/css"" href=""/_layouts/INC/MS.InformationManagement/css/layoutInterna.css"" />" };
                input.Controls.Add(cssFile);
            }
        }

        public static void OpenWindowSearchRadicado(this HyperLink input, string url, string callbackMethod)
        {
            StringBuilder scriptModal = new StringBuilder();
            scriptModal.Append("var showMyModalDialog = function() { var options = { ");
            scriptModal.Append("autosize : true,");
            scriptModal.Append(string.Format("url : '{0}',", url));
            scriptModal.Append(string.Format("dialogReturnValueCallback: {0} }}; SP.UI.ModalDialog.commonModalDialogOpen('{1}',options, {2}, null); }};", callbackMethod, url, callbackMethod));
            input.Page.ClientScript.RegisterClientScriptBlock(input.Page.GetType(), "SearchSenderPopUp", scriptModal.ToString(), true);
            input.NavigateUrl = "javascript:showMyModalDialog()";
        }

        public static void AddLoader(this Button button)
        {
            StringBuilder javascript = new StringBuilder();
            javascript
                .Append("<script type='text/javascript'>")
                .Append("$(document).ready(function(){")
                .Append("$('#" + button.ClientID + "').ajaxloader({ fullscreen: true, baseurl: '/sites/docs/', autoshow: false, usealternatesettings: true });")
                .Append("$('#" + button.ClientID + "').click(function(){");
            if (string.IsNullOrEmpty(button.ValidationGroup))
            {
                javascript.Append("$(this).ajaxloader('show');");
            }
            else
            {
                javascript
                    .Append(string.Format("var {0}_isValid = Page_ClientValidate('{1}');", button.ClientID, button.ValidationGroup))
                    .Append(string.Format("if({0}_isValid === true)", button.ClientID))
                    .Append("{")
                    .Append("$(this).ajaxloader('show');")
                    .Append("}");
            }
            javascript
                .Append("});")
                .Append("});</script>");
            button.Page.ClientScript.RegisterClientScriptBlock(button.GetType(), string.Format("loader_{0}", button.ClientID), javascript.ToString());
        }

        public static void AddLoader(this ImageButton button)
        {
            StringBuilder javascript = new StringBuilder();
            javascript
                .Append("<script type='text/javascript'>")
                .Append("$(document).ready(function(){")
                .Append("$('#" + button.ClientID + "').ajaxloader({ fullscreen: true, baseurl: '/sites/docs/', autoshow: false, usealternatesettings: true });")
                .Append("$('#" + button.ClientID + "').click(function(){");
            if (string.IsNullOrEmpty(button.ValidationGroup))
            {
                javascript.Append("$(this).ajaxloader('show');");
            }
            else
            {
                javascript
                    .Append(string.Format("var {0}_isValid = Page_ClientValidate('{1}');", button.ClientID, button.ValidationGroup))
                    .Append(string.Format("if({0}_isValid === true)", button.ClientID))
                    .Append("{")
                    .Append("$(this).ajaxloader('show');")
                    .Append("}");
            }
            javascript
                .Append("});")
                .Append("});</script>");

            button.Page.ClientScript.RegisterClientScriptBlock(button.GetType(), string.Format("loader_{0}", button.ClientID), javascript.ToString());
        }

        public static void AddLoader(this DropDownList dropdownlist)
        {
            StringBuilder javascript = new StringBuilder();
            javascript
                .Append("<script type='text/javascript'>")
                .Append("$(document).ready(function(){")
                .Append("$('#" + dropdownlist.ClientID + "').ajaxloader({ fullscreen: true, baseurl: '/sites/docs/', autoshow: false, usealternatesettings: true });")
                .Append("$('#" + dropdownlist.ClientID + "').change(function(){");
            if (string.IsNullOrEmpty(dropdownlist.ValidationGroup))
            {
                javascript.Append("$(this).ajaxloader('show');");
            }
            else
            {
                javascript
                    .Append(string.Format("var {0}_isValid = Page_ClientValidate('{1}');", dropdownlist.ClientID, dropdownlist.ValidationGroup))
                    .Append(string.Format("if({0}_isValid === true)", dropdownlist.ClientID))
                    .Append("{")
                    .Append("$(this).ajaxloader('show');")
                    .Append("}");
            }
            javascript
                .Append("});")
                .Append("});</script>");

            dropdownlist.Page.ClientScript.RegisterClientScriptBlock(dropdownlist.GetType(), string.Format("loader_{0}", dropdownlist.ClientID), javascript.ToString());
        }

        public static void AddLoader(this LinkButton button)
        {
            StringBuilder javascript = new StringBuilder();
            javascript
                .Append("<script type='text/javascript'>")
                .Append("$(document).ready(function(){")
                .Append("$('#" + button.ClientID + "').ajaxloader({ fullscreen: true, baseurl: '/sites/docs/', autoshow: false, usealternatesettings: true });")
                .Append("$('#" + button.ClientID + "').click(function(){");
            if (string.IsNullOrEmpty(button.ValidationGroup))
            {
                javascript.Append("$(this).ajaxloader('show');");
            }
            else
            {
                javascript
                    .Append(string.Format("var {0}_isValid = Page_ClientValidate('{1}');", button.ClientID, button.ValidationGroup))
                    .Append(string.Format("if({0}_isValid === true)", button.ClientID))
                    .Append("{")
                    .Append("$(this).ajaxloader('show');")
                    .Append("}");
            }
            javascript
                .Append("});")
                .Append("});</script>");
            button.Page.ClientScript.RegisterClientScriptBlock(button.GetType(), string.Format("loader_{0}", button.ClientID), javascript.ToString());

        }

        public static void AddLoader(this Button button, string containerDOMElementID)
        {
            StringBuilder javascript = new StringBuilder();
            javascript
                .Append("<script type='text/javascript'>")
                .Append("$(document).ready(function(){")
                .Append("$('#" + containerDOMElementID + "').ajaxloader({ fullscreen: false, baseurl: '/sites/docs/', autoshow: false, usealternatesettings: true });")
                .Append("$('#" + button.ClientID + "').click(function(){");
            if (string.IsNullOrEmpty(button.ValidationGroup))
            {
                javascript.Append("$('#" + containerDOMElementID + "').ajaxloader('show');");
            }
            else
            {
                javascript
                    .Append(string.Format("var {0}_isValid = Page_ClientValidate('{1}');", button.ClientID, button.ValidationGroup))
                    .Append(string.Format("if({0}_isValid === true)", button.ClientID))
                    .Append("{")
                    .Append("$('#" + containerDOMElementID + "').ajaxloader('show');")
                    .Append("}");
            }
            javascript
                .Append("});")
                .Append("});</script>");
            button.Page.ClientScript.RegisterClientScriptBlock(button.GetType(), string.Format("loader_{0}", button.ClientID), javascript.ToString());
        }

        public static void AddLoader(this ImageButton button, string containerDOMElementID)
        {
            StringBuilder javascript = new StringBuilder();
            javascript
                .Append("<script type='text/javascript'>")
                .Append("$(document).ready(function(){")
                .Append("$('#" + containerDOMElementID + "').ajaxloader({ fullscreen: false, baseurl: '/sites/docs/', autoshow: false, usealternatesettings: true });")
                .Append("$('#" + button.ClientID + "').click(function(){");
            if (string.IsNullOrEmpty(button.ValidationGroup))
            {
                javascript.Append("$('#" + containerDOMElementID + "').ajaxloader('show');");
            }
            else
            {
                javascript
                    .Append(string.Format("var {0}_isValid = Page_ClientValidate('{1}');", button.ClientID, button.ValidationGroup))
                    .Append(string.Format("if({0}_isValid === true)", button.ClientID))
                    .Append("{")
                    .Append("$('#" + containerDOMElementID + "').ajaxloader('show');")
                    .Append("}");
            }
            javascript
                .Append("});")
                .Append("});</script>");
            button.Page.ClientScript.RegisterClientScriptBlock(button.GetType(), string.Format("loader_{0}", button.ClientID), javascript.ToString());
        }

        public static void AddLoader(this LinkButton button, string containerDOMElementID)
        {
            StringBuilder javascript = new StringBuilder();
            javascript
                .Append("<script type='text/javascript'>")
                .Append("$(document).ready(function(){")
                .Append("$('#" + containerDOMElementID + "').ajaxloader({ fullscreen: false, baseurl: '/sites/docs/', autoshow: false, usealternatesettings: true });")
                .Append("$('#" + button.ClientID + "').click(function(){");
            if (string.IsNullOrEmpty(button.ValidationGroup))
            {
                javascript.Append("$('#" + containerDOMElementID + "').ajaxloader('show');");
            }
            else
            {
                javascript
                    .Append(string.Format("var {0}_isValid = Page_ClientValidate('{1}');", button.ClientID, button.ValidationGroup))
                    .Append(string.Format("if({0}_isValid === true)", button.ClientID))
                    .Append("{")
                    .Append("$('#" + containerDOMElementID + "').ajaxloader('show');")
                    .Append("}");
            }
            javascript
                .Append("});")
                .Append("});</script>");
            button.Page.ClientScript.RegisterClientScriptBlock(button.GetType(), string.Format("loader_{0}", button.ClientID), javascript.ToString());
        }

        public static void AddLoader(this DropDownList dropdownlist, string containerDOMElementID)
        {
            StringBuilder javascript = new StringBuilder();
            javascript
                .Append("<script type='text/javascript'>")
                .Append("$(document).ready(function(){")
                .Append("$('#" + containerDOMElementID + "').ajaxloader({ fullscreen: false, baseurl: '/sites/docs/', autoshow: false, usealternatesettings: true });")
                .Append("$('#" + dropdownlist.ClientID + "').change(function(){");
            if (string.IsNullOrEmpty(dropdownlist.ValidationGroup))
            {
                javascript.Append("$('#" + containerDOMElementID + "').ajaxloader('show');");
            }
            else
            {
                javascript
                    .Append(string.Format("var {0}_isValid = Page_ClientValidate('{1}');", dropdownlist.ClientID, dropdownlist.ValidationGroup))
                    .Append(string.Format("if({0}_isValid === true)", dropdownlist.ClientID))
                    .Append("{")
                    .Append("$('#" + containerDOMElementID + "').ajaxloader('show');")
                    .Append("}");
            }
            javascript
                .Append("});")
                .Append("});</script>");
            dropdownlist.Page.ClientScript.RegisterClientScriptBlock(dropdownlist.GetType(), string.Format("loader_{0}", dropdownlist.ClientID), javascript.ToString());
        }

        #region Ribbon Configuration



        static string ContextualTemplate = @"<GroupTemplate Id=""Ribbon.Templates.BoundTemplate"">
            <Layout
              Title=""BasedLayout""
              LayoutTitle=""BasedLayout"">
              <Section Alignment=""Top"" Type=""OneRow"">
                <Row>
                  <ControlRef DisplayMode=""Large"" TemplateAlias=""homeButton"" />
                  <ControlRef DisplayMode=""Large"" TemplateAlias=""expedientesButton""/>
                  <ControlRef DisplayMode=""Large"" TemplateAlias=""inputButton"" />
                  <ControlRef DisplayMode=""Large"" TemplateAlias=""templateRadicadoSalidaButton"" />
                  <ControlRef DisplayMode=""Large"" TemplateAlias=""outputButton"" />
                  <ControlRef DisplayMode=""Large"" TemplateAlias=""templategeneratorButton"" />
                  <ControlRef DisplayMode=""Large"" TemplateAlias=""solicitudAnulacionButton"" />
                  <ControlRef DisplayMode=""Large"" TemplateAlias=""radicadosAnuladosButton"" />
                  <ControlRef DisplayMode=""Large"" TemplateAlias=""PrestamosButton"" />
<ControlRef DisplayMode=""Large"" TemplateAlias=""receptionButton"" />
                  <ControlRef DisplayMode=""Large"" TemplateAlias=""PrintButton"" />
                </Row>
              </Section>
            </Layout>
          </GroupTemplate>";

        static string ContextualTemplate2 = @"<GroupTemplate Id=""Ribbon.Templates.DocumentSchedulingTemplate"">
            <Layout
              Title=""DocumentScheduleLayout""
              LayoutTitle=""DocumentScheduleLayout"">
              <Section Alignment=""Top"" Type=""OneRow"">
                <Row>
                  <ControlRef DisplayMode=""Large"" TemplateAlias=""viewScheduleButton"" />
                </Row>
              </Section>
              <Section Type=""OneRow"" Alignment=""Top"">
                <Row>
                  <ControlRef DisplayMode=""Large"" TemplateAlias=""scheduleDocumentsButton"" />
                </Row>
              </Section>
            </Layout>
          </GroupTemplate>";

        static string ContextTualTemplate3 = @"<GroupTemplate Id=""Ribbon.Templates.DocumentActionsTemplate"">
            <Layout
              Title=""DocumentActionsLayout""
              LayoutTitle=""DocumentActionsLayout"">
              <Section Alignment=""Top"" Type=""TwoRow"">
                <Row>
                  <ControlRef DisplayMode=""Medium"" TemplateAlias=""moveDocumentsButton"" />
                  <ControlRef DisplayMode=""Medium"" TemplateAlias=""vbDocumentsButton"" />
                </Row>
                <Row>
                  <ControlRef DisplayMode=""Medium"" TemplateAlias=""informDocumentsButton"" />
                  <ControlRef DisplayMode=""Medium"" TemplateAlias=""includeButton"" />
                </Row>
               </Section>
            </Layout>
        </GroupTemplate>";

        //        public static string ContextualTemplateScanning = @"<GroupTemplate Id=""Ribbon.Templates.Scanning"">
        //            <Layout
        //              Title=""ScanningLayout""
        //              LayoutTitle=""ScanningLayout"">
        //              <Section Alignment=""Top"" Type=""OneRow"">
        //                <Row>
        //                  <ControlRef DisplayMode=""Large"" TemplateAlias=""ScanningDocuments"" />
        //                </Row>
        //              </Section>
        //            </Layout>
        //          </GroupTemplate>";

        public static string ContextualTemplateAnulados = @"<GroupTemplate Id=""Ribbon.Templates.DocumentShipping"">
            <Layout
              Title=""DocumentShippingLayout""
              LayoutTitle=""DocumentShippingLayout"">
              <Section Alignment=""Top"" Type=""OneRow"">
                <Row>
                  <ControlRef DisplayMode=""Large"" TemplateAlias=""_EnviosButton"" />
                </Row>
              </Section>
            </Layout>
          </GroupTemplate>";

        public static void AddRibbonActionPage(Page input, Dictionary<string, string> agregarAcciones)
        {
            addRibbon(input, agregarAcciones);
        }

        public static void AddRibbonActions(this LayoutsPageBase Input)
        {
            addRibbon(Input);
        }

        public static void AddRibbonActions(this UserControl Input)
        {
            addRibbon(Input.Page);
        }


        private static void addRibbon(Page input)
        {
            if (input.Page.Request.QueryString["IsDlg"] == "1") return;
            addRibbonTab(input);
            addEvents(input);
        }
        private static void addRibbon(Page input, Dictionary<string, string> agregarAcciones)
        {
            if (input.Page.Request.QueryString["IsDlg"] == "1") return;
            addRibbonTab(input, agregarAcciones);
            addEvents(input);
        }

        private static void addRibbonTab(Page currentPage)
        {
            // Gets the current instance of the ribbon on the page.
            SPRibbon ribbon = SPRibbon.GetCurrent(currentPage);

            //Prepares an XmlDocument object used to load the ribbon
            XmlDocument ribbonExtensions = new XmlDocument();

            string strategy = currentPage.Request.QueryString["strategy"];

            //if (((SPContext.Current.List == null) || !string.IsNullOrEmpty(strategy) || (SPContext.Current.List != null && !SPContext.Current.List.BaseTemplate.ToString().Equals(GlobalConstants.GLOBAL_USER_LIBRARY_TEMPLATE))))
            //{
            addGlobalTabOption(ribbonExtensions, ribbon);
            ribbon.Minimized = false;
            ribbon.CommandUIVisible = true;
            const string initialTabId1 = "MSIM";
            if (!ribbon.IsTabAvailable(initialTabId1))
                ribbon.MakeTabAvailable(initialTabId1);
            ribbon.InitialTabId = initialTabId1;
            //}

            if (SPContext.Current.Web.CurrentUser.IsSiteAdmin)
            {
                addAdministration(ribbonExtensions, ribbon);
                ribbon.Minimized = false;
                ribbon.CommandUIVisible = true;
                const string initialTabId = "MSIMADM";
                if (!ribbon.IsTabAvailable(initialTabId))
                    ribbon.MakeTabAvailable(initialTabId);
            }

            AddDeliveries(ribbonExtensions, ribbon);
            ribbon.Minimized = false;
            ribbon.CommandUIVisible = true;
            const string deliveryTabId = "MSIMD";
            if (!ribbon.IsTabAvailable(deliveryTabId))
                ribbon.MakeTabAvailable(deliveryTabId);
        }

        private static void addRibbonTab(Page currentPage, Dictionary<string, string> agregarAcciones)
        {
            // Gets the current instance of the ribbon on the page.
            SPRibbon ribbon = SPRibbon.GetCurrent(currentPage);

            //Prepares an XmlDocument object used to load the ribbon
            XmlDocument ribbonExtensions = new XmlDocument();

            string strategy = currentPage.Request.QueryString["strategy"];

            //if (((SPContext.Current.List == null) || !string.IsNullOrEmpty(strategy) || (SPContext.Current.List != null && !SPContext.Current.List.BaseTemplate.ToString().Equals(GlobalConstants.GLOBAL_USER_LIBRARY_TEMPLATE))))
            //{
            bool gestionDoc = false;
            bool correspondencia = false;
            string tab = string.Empty;
            foreach (var item in agregarAcciones)
            {
                if (!string.IsNullOrEmpty(item.Value))
                {
                    tab = item.Value;
                    switch (tab)
                    {
                        case "GestionDocumental":
                            gestionDoc = true;
                            break;
                        case "Correspondencia":
                            correspondencia = true;
                            break;
                    }

                }
            }
            if (gestionDoc)
            {
                addGlobalTabOption(ribbonExtensions, ribbon);
                ribbon.Minimized = false;
                ribbon.CommandUIVisible = true;
                const string initialTabId1 = "MSIM";
                if (!ribbon.IsTabAvailable(initialTabId1))
                    ribbon.MakeTabAvailable(initialTabId1);
                ribbon.InitialTabId = initialTabId1;
            }

            if (SPContext.Current.Web.CurrentUser.IsSiteAdmin)
            {
                addAdministration(ribbonExtensions, ribbon);
                ribbon.Minimized = false;
                ribbon.CommandUIVisible = true;
                const string initialTabId = "MSIMADM";
                if (!ribbon.IsTabAvailable(initialTabId))
                    ribbon.MakeTabAvailable(initialTabId);
            }

            if (correspondencia)
            {
                AddDeliveries(ribbonExtensions, ribbon);
                ribbon.Minimized = false;
                ribbon.CommandUIVisible = true;
                const string deliveryTabId = "MSIMD";
                if (!ribbon.IsTabAvailable(deliveryTabId))
                    ribbon.MakeTabAvailable(deliveryTabId);
            }
        }

        private static void addEvents(Page currentPage)
        {
            var commands = new List<IRibbonCommand>();
            if ((SPContext.Current.List != null) || ((SPContext.Current.List == null) || (SPContext.Current.List != null && !SPContext.Current.List.BaseTemplate.ToString().Equals(GlobalConstants.GLOBAL_USER_LIBRARY_TEMPLATE))))
                addGlobalTabEvents(commands);

            if (SPContext.Current.Web.CurrentUser.IsSiteAdmin)
                addAdminTabEvents(commands);

            addDeliveryTabEvents(commands);

            var manager = new SPRibbonScriptManager();
            ScriptLink.RegisterScriptAfterUI(currentPage, "SP.Runtime.js", false, true);
            ScriptLink.RegisterScriptAfterUI(currentPage, "SP.js", false, true);
            ScriptLink.RegisterScriptAfterUI(currentPage, "CUI.js", false, true);
            ScriptLink.RegisterScriptAfterUI(currentPage, "SP.Ribbon.js", false, true);

            var methodInfo = typeof(SPRibbonScriptManager).GetMethod("RegisterInitializeFunction", BindingFlags.Instance | BindingFlags.NonPublic);
            methodInfo.Invoke(manager, new object[]{currentPage,
                                                   "InitPageComponent",
                                                   "/_layouts/INC/MS.InformationManagement/JS/PageComponent.js",
                                                   false,
                                                   "RibbonCustomization.PageComponent.initialize()"});


            //manager.RegisterGetCommandsFunction(currentPage, "getGlobalCommands", commands);
            //manager.RegisterCommandEnabledFunction(currentPage, "commandEnabled", commands);
            //manager.RegisterHandleCommandFunction(currentPage, "handleCommand", commands);

            //Register redirect function
            StringBuilder sb = new StringBuilder()
            .Append("<script type='text/javascript'>function ribbonRedired(url){")
            .Append("window.location=url")
            .Append("}</script>");
            currentPage.ClientScript.RegisterStartupScript(sb.GetType(), "redirectRibbonFunction", sb.ToString(), false);
            RegisterGetCommandsFunction(currentPage, commands);
            RegisterCommandEnabledFunction(currentPage, commands);
            RegisterHandleCommandFunction(currentPage, commands);
        }

        private static void RegisterCommandEnabledFunction(Page page, IEnumerable<IRibbonCommand> commands)
        {
            StringBuilder javascript = new StringBuilder("<script type='text/javascript'>");
            StringBuilder emptyEnabledStatementJavascriptBuilder = null;
            StringBuilder enableStatementJavascriptBuilder = null;

            var emptyEnabledStatementCommands = from cmd in commands
                                                where string.IsNullOrEmpty(cmd.EnabledStatement)
                                                select cmd;
            var enableStatementCommands = from cmd in commands
                                          where !string.IsNullOrEmpty(cmd.EnabledStatement)
                                          select cmd;

            javascript.Append("function commandEnabled(commandId){");

            if (emptyEnabledStatementCommands.Count() > 0)
            {
                emptyEnabledStatementJavascriptBuilder = new StringBuilder("if(");
                foreach (IRibbonCommand cmd in emptyEnabledStatementCommands)
                {
                    emptyEnabledStatementJavascriptBuilder.Append(string.Format("(commandId === '{0}') || ", cmd.Id));
                }
                emptyEnabledStatementJavascriptBuilder.Remove(emptyEnabledStatementJavascriptBuilder.Length - 4, 4);
                emptyEnabledStatementJavascriptBuilder.Append("){ return true; }");
            }

            if (enableStatementCommands.Count() > 0)
            {
                enableStatementJavascriptBuilder = new StringBuilder();
                foreach (IRibbonCommand cmd in enableStatementCommands)
                {
                    enableStatementJavascriptBuilder.Append(string.Format("if (commandId === '{0}') return {1};", cmd.Id, cmd.EnabledStatement));
                }
            }

            if (emptyEnabledStatementJavascriptBuilder != null) { javascript.Append(emptyEnabledStatementJavascriptBuilder.ToString()); }
            if (enableStatementJavascriptBuilder != null) { javascript.Append(enableStatementJavascriptBuilder.ToString()); }
            javascript.Append("return false; }");
            javascript.Append("</script>");

            page.ClientScript.RegisterStartupScript(typeof(WindowExtensionHelper), "RegisterCommandEnabledFunction", javascript.ToString(), false);

        }

        private static void RegisterGetCommandsFunction(Page page, IEnumerable<IRibbonCommand> commands)
        {
            StringBuilder javascript = new StringBuilder("<script type='text/javascript'>");
            javascript
                .Append("function getGlobalCommands(){")
                .Append("return [");
            foreach (IRibbonCommand cmd in commands)
            {
                javascript.Append(string.Format("'{0}',", cmd.Id));
            }
            javascript.Remove(javascript.Length - 1, 1);
            javascript
                .Append("];")
                .Append("}")
                .Append("</script>");

            page.ClientScript.RegisterStartupScript(typeof(WindowExtensionHelper), "RegisterGetCommandsFunction", javascript.ToString(), false);
        }

        private static void RegisterHandleCommandFunction(Page page, IEnumerable<IRibbonCommand> commands)
        {
            StringBuilder javascript = new StringBuilder("<script type ='text/javascript'>");
            StringBuilder handledCommandsJavascript = null;

            javascript.Append("function handleCommand(commandId, properties, sequence) {");

            var handledCommands = from cmd in commands
                                  where !string.IsNullOrEmpty(cmd.HandlerStatement)
                                  select cmd;

            if (handledCommands.Count() > 0)
            {
                handledCommandsJavascript = new StringBuilder();
                handledCommandsJavascript.Append("switch(commandId){");
                foreach (IRibbonCommand cmd in commands)
                {
                    handledCommandsJavascript.Append(string.Format("case '{0}': {1}; break;", cmd.Id, cmd.HandlerStatement));
                }
                handledCommandsJavascript
                    .Append("default: return false; break;")
                    .Append("}");
            }
            if (handledCommandsJavascript != null) { javascript.Append(handledCommandsJavascript.ToString()); }
            javascript
                .Append("}")
                .Append("</script>");

            page.ClientScript.RegisterStartupScript(typeof(WindowExtensionHelper), "RegisterHandleCommandFunction", javascript.ToString(), false);
        }

        public static void addGlobalTabEvents(List<IRibbonCommand> commands)
        {
            commands.Add(new SPRibbonCommand("AdminGroup.GoToCentralAdministration", "ribbonRedired('/sites/docs/pages/ADMINISTRACIONUSUARIOS.aspx')"));

            commands.Add(new SPRibbonCommand("BasedGroup.Expedientes", "ribbonRedired('/Sites/Docs/_layouts/MS.InformationManagement.WP/ExpedientesManager.aspx?InitialTabId=MSIM&VisibilityContext=WSSTabPersistence')"));
            commands.Add(new SPRibbonCommand("BasedGroup.InputCommand", "ribbonRedired('/sites/docs/_layouts/MS.InformationManagement.WP/InsertarRadicado.aspx?InitialTabId=MSIM&VisibilityContext=WSSTabPersistence')"));
            commands.Add(new SPRibbonCommand("BasedGroup.TemplateGeneratorCommand", string.Format("openDialogAutoSize('/sites/docs/_layouts/MS.InformationManagement.WP/DocumentGenerator.aspx?lstID={0}')", ListHelper.GetUserList(SPContext.Current.Web.CurrentUser.LoginName) == null ? string.Empty : ListHelper.GetUserList(SPContext.Current.Web.CurrentUser.LoginName).ID.ToString())));
            commands.Add(new SPRibbonCommand("BasedGroup.RadicadoSalidaCommand", "ribbonRedired('/sites/docs/_layouts/MS.InformationManagement.WP/InsertarRadicadoSalida.aspx?InitialTabId=MSIM&VisibilityContext=WSSTabPersistence')"));
            commands.Add(new SPRibbonCommand("BasedGroup.Home", "ribbonRedired('/sites/docs/')"));
            commands.Add(new SPRibbonCommand("BasedGroup.Reception", "ribbonRedired('/sites/docs/_layouts/MS.InformationManagement.WP/DistribuirRadicado.aspx?InitialTabId=MSIM&VisibilityContext=WSSTabPersistence')"));




            commands.Add(new SPRibbonCommand("DocumentActionGroup.InformDocument", string.Format("openDialogAutoSize('/sites/docs/_Layouts/MS.InformationManagement.WP/RequestInformation.aspx?lstID={0}'+ MS.InformationManagement.Ribbon.GetItemsIDQueryString());", ListHelper.GetUserList(SPContext.Current.Web.CurrentUser.LoginName) == null ? string.Empty : ListHelper.GetUserList(SPContext.Current.Web.CurrentUser.LoginName).ID.ToString()), "MS.InformationManagement.Ribbon.EnableButtonContent('Radicado Interno,Radicado Empresa,Radicado Persona,Radicado Empresa Salida,Radicado Persona Salida');"));
            commands.Add(new SPRibbonCommand("DocumentActionGroup.MoveDocument", string.Format("openDialogAutoSize('/sites/docs/_Layouts/MS.InformationManagement.WP/ReasignarDocumento.aspx?lstID={0}'+ MS.InformationManagement.Ribbon.GetItemsIDQueryString());", ListHelper.GetUserList(SPContext.Current.Web.CurrentUser.LoginName) == null ? string.Empty : ListHelper.GetUserList(SPContext.Current.Web.CurrentUser.LoginName).ID.ToString()), "MS.InformationManagement.Ribbon.EnableButtonContent('Radicado Interno,Radicado Empresa,Radicado Persona,Radicado Empresa Salida,Radicado Persona Salida');"));
            commands.Add(new SPRibbonCommand("DocumentActionGroup.AddToRecord", "openDialogAutoSize('/sites/docs/_Layouts/MS.InformationManagement.WP/IncludeInRecord.aspx?'+ MS.InformationManagement.Ribbon.GetItemsIDQueryString());", "MS.InformationManagement.Ribbon.EnableButtonContent('Radicado Interno,Radicado Empresa,Radicado Persona,Radicado Empresa Salida,Radicado Persona Salida');"));

            commands.Add(new SPRibbonCommand("DocumentSchedulingGroup.ScheduleDocument", string.Format("MS.InformationManagement.Ribbon.DocumentScheduler.ScheduleDocuments('{0}', '{1}');", SPContext.Current.Web.Url, ListHelper.GetUserList(SPContext.Current.Web.CurrentUser.LoginName) == null ? string.Empty : ListHelper.GetUserList(SPContext.Current.Web.CurrentUser.LoginName).ID.ToString()), "MS.InformationManagement.Ribbon.EnableButtonContent('Radicado Interno,Radicado Empresa,Radicado Persona')&&MS.InformationManagement.Ribbon.EnableSchedulerButtonContent();"));
            commands.Add(new SPRibbonCommand("DocumentSchedulingGroup.ViewSchedule", string.Format("MS.InformationManagement.Ribbon.DocumentScheduler.OpenSchedulerModal('{0}','{1}')", SPContext.Current.Web.Url, ListHelper.GetUserList(SPContext.Current.Web.CurrentUser.LoginName) == null ? string.Empty : ListHelper.GetUserList(SPContext.Current.Web.CurrentUser.LoginName).ID.ToString())));


        }

        public static void addAdminTabEvents(List<IRibbonCommand> commands)
        {
            commands.Add(new SPRibbonCommand("Profiles.Profiles", "ribbonRedired('/sites/docs/_layouts/MS.InformationManagement.WP/GestionPerfiles.aspx?InitialTabId=MSIMADM&VisibilityContext=WSSTabPersistence')"));
            commands.Add(new SPRibbonCommand("Profiles.Roles", "ribbonRedired('/sites/docs/Lists/Roles/AllItems.aspx?InitialTabId=MSIMADM&VisibilityContext=WSSTabPersistence')"));
            commands.Add(new SPRibbonCommand("Users.Users", "ribbonRedired('/Sites/Docs/_layouts/MS.InformationManagement.WP/SearchUser.aspx?InitialTabId=MSIMADM&VisibilityContext=WSSTabPersistence')"));
            commands.Add(new SPRibbonCommand("Contacts.Contacts", "ribbonRedired('/sites/docs/Lists/Contactos Externos/AllItems.aspx?InitialTabId=MSIMADM&VisibilityContext=WSSTabPersistence')"));
            commands.Add(new SPRibbonCommand("Correspondencia.SentKind", "ribbonRedired('/sites/docs/Tipos Documentales/Forms/AllItems.aspx?InitialTabId=MSIMADM&VisibilityContext=WSSTabPersistence')"));
            commands.Add(new SPRibbonCommand("Correspondencia.Edicion", "ribbonRedired('/sites/docs/')"));
            commands.Add(new SPRibbonCommand("Correspondencia.Costs", "ribbonRedired('/sites/docs/')"));
            commands.Add(new SPRibbonCommand("Correspondencia.Festivos", "ribbonRedired('/sites/docs/Lists/Dias%20Festivos/AllItems.aspx?InitialTabId=MSIMADM&VisibilityContext=WSSTabPersistence')"));
            commands.Add(new SPRibbonCommand("Correspondencia.ConfCostos", "ribbonRedired('/sites/docs/_layouts/MS.InformationManagement.WP/DeliveryMeanConfiguration.aspx?InitialTabId=MSIMADM&VisibilityContext=WSSTabPersistence')"));
            commands.Add(new SPRibbonCommand("Correspondencia.ConfConsecutivos", "ribbonRedired('/sites/docs/_layouts/MS.InformationManagement.WP/StandardDocumentIdConfiguration.aspx?InitialTabId=MSIMADM&VisibilityContext=WSSTabPersistence')"));
            commands.Add(new SPRibbonCommand("MassiveUploads.BackdropUpload", "openDialogAutoSize('/sites/docs/_layouts/MS.InformationManagement.WP/cargamasivadefondos.aspx')"));
            commands.Add(new SPRibbonCommand("MassiveUploads.SeriesUpload", "openDialogAutoSize('/sites/docs/_layouts/MS.InformationManagement.WP/cargamasivadeseries.aspx')"));
            commands.Add(new SPRibbonCommand("MassiveUploads.SectionsUpload", "openDialogAutoSize('/sites/docs/_layouts/MS.InformationManagement.WP/cargamasivadesecciones.aspx')"));
            commands.Add(new SPRibbonCommand("MassiveUploads.SubseriesUpload", "openDialogAutoSize('/sites/docs/_layouts/MS.InformationManagement.WP/cargamasivadesubseries.aspx')"));
            commands.Add(new SPRibbonCommand("MassiveUploads.PeopleUpload", "openDialogAutoSize('/sites/docs/_layouts/MS.InformationManagement.WP/cargamasivadepersonas.aspx')"));
            commands.Add(new SPRibbonCommand("MassiveUploads.EntitiesUpload", "openDialogAutoSize('/sites/docs/_layouts/MS.InformationManagement.WP/cargamasivadeentidades.aspx')"));
            //commands.Add(new SPRibbonCommand("BasedGroup.RadicadosAnulados", "ribbonRedired('/Sites/docs/_layouts/MS.InformationManagement.WP/RadicadosAnulados.aspx?InitialTabId=MSIMADM&VisibilityContext=WSSTabPersistence')"));

            //--> Solo Azteca commands.Add(new SPRibbonCommand("Correspondencia.Zonas", "ribbonRedired('/sites/docs/Lists/Zonas/AllItems.aspx?InitialTabId=MSIMADM&VisibilityContext=WSSTabPersistence')"));
            commands.Add(new SPRibbonCommand("TRD.Fondos", "ribbonRedired('/sites/docs/Lists/Backdrops/AllItems.aspx?InitialTabId=MSIMADM&VisibilityContext=WSSTabPersistence')"));
            commands.Add(new SPRibbonCommand("TRD.Seccion", "ribbonRedired('/sites/docs/Lists/Sections/AllItems.aspx?InitialTabId=MSIMADM&VisibilityContext=WSSTabPersistence')"));
            commands.Add(new SPRibbonCommand("TRD.Series", "ribbonRedired('/sites/docs/Lists/Series/AllItems.aspx?InitialTabId=MSIMADM&VisibilityContext=WSSTabPersistence')"));
            commands.Add(new SPRibbonCommand("TRD.Subseries", "ribbonRedired('/sites/docs/Lists/SubSeries/AllItems.aspx?InitialTabId=MSIMADM&VisibilityContext=WSSTabPersistence')"));
            commands.Add(new SPRibbonCommand("TRD.DocumentalType", "ribbonRedired('/sites/docs/Tipos Documentales/Forms/AllItems.aspx?InitialTabId=MSIMADM&VisibilityContext=WSSTabPersistence')"));
            commands.Add(new SPRibbonCommand("TRD.TRD", "ribbonRedired('/sites/docs/_layouts/MS.InformationManagement.WP/TRDConfigItemsGrid.aspx?InitialTabId=MSIMADM&VisibilityContext=WSSTabPersistence')"));

        }

        public static void addDeliveryTabEvents(List<IRibbonCommand> commands)
        {
            commands.Add(new SPRibbonCommand("Deliveries.DeliverySheets", "ribbonRedired('/sites/docs/Lists/Distribucion/AllItems.aspx?InitialTabId=MSIMD&VisibilityContext=WSSTabPersistence')"));

        }

        public static void addGlobalTabOption(XmlDocument ribbonExtensions, SPRibbon ribbon)
        {
            //Load the contextual tab XML and register the ribbon.
            ribbonExtensions.LoadXml(RibbonDefinitions.MainTab);
            ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.Tabs._children");

            //Load the custom templates and register the ribbon.
            ribbonExtensions.LoadXml(ContextualTemplate);
            ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.Templates._children");

            //ribbonExtensions.LoadXml(ContextualTemplate1);
            //ribbon.RegisterDataExtension(ribbonExtensions.LastChild, "Ribbon.Templates._children");

            ribbonExtensions.LoadXml(ContextualTemplate2);
            ribbon.RegisterDataExtension(ribbonExtensions.LastChild, "Ribbon.Templates._children");

            ribbonExtensions.LoadXml(ContextTualTemplate3);
            ribbon.RegisterDataExtension(ribbonExtensions.LastChild, "Ribbon.Templates._children");

            //ribbonExtensions.LoadXml(ContextualTemplateScanning);
            //ribbon.RegisterDataExtension(ribbonExtensions.LastChild, "Ribbon.Templates._children");

            ribbonExtensions.LoadXml(ContextualTemplateAnulados);
            ribbon.RegisterDataExtension(ribbonExtensions.LastChild, "Ribbon.Templates._children");

        }

        public static void addAdministration(XmlDocument ribbonExtensions, SPRibbon ribbon)
        {
            ribbonExtensions.LoadXml(RibbonDefinitions.AdministrationTab);
            ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.Tabs._children");

            ribbonExtensions.LoadXml(RibbonDefinitions.ContextualTemplateProfile);
            ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.Templates._children");

            ribbonExtensions.LoadXml(RibbonDefinitions.ContextualTemplateUsers);
            ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.Templates._children");

            ribbonExtensions.LoadXml(RibbonDefinitions.ContextualTemplateContacts);
            ribbon.RegisterDataExtension(ribbonExtensions.LastChild, "Ribbon.Templates._children");

            ribbonExtensions.LoadXml(RibbonDefinitions.ContextualTemplateCorrespondencia);
            ribbon.RegisterDataExtension(ribbonExtensions.LastChild, "Ribbon.Templates._children");

            ribbonExtensions.LoadXml(RibbonDefinitions.ContextualTemplateMassiveUploads);
            ribbon.RegisterDataExtension(ribbonExtensions.LastChild, "Ribbon.Templates._children");

            ribbonExtensions.LoadXml(RibbonDefinitions.ContextualTemplateTRD);
            ribbon.RegisterDataExtension(ribbonExtensions.LastChild, "Ribbon.Templates._children");

        }

        public static void AddDeliveries(XmlDocument ribbonExtensions, SPRibbon ribbon)
        {
            ribbonExtensions.LoadXml(RibbonDefinitions.DeliveriesTab);
            ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.Tabs._children");

            ribbonExtensions.LoadXml(RibbonDefinitions.ContextualTemplateDeliveries);
            ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.Templates._children");

            //ribbonExtensions.LoadXml(RibbonDefinitions.ContextualTemplatePrinting);
            //ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.Templates._children");
        }

        #endregion

    }
}
